<template>
  <base-modal :title="title" :show.sync="dialogVisible" width="600px" @closed="dialogVisible = false">
    <div class="base-mode-wrap">
      <div class="prev-level-des">
        <div class="label">{{ $t('faultLibrary.faultObject.label4') }}</div>
        <el-input disabled v-model="parentDesc" />
      </div>

      <form-builder
        v-loading="loading"
        :fields="fields"
        ref="ruleForm"
        :value="ruleForm"
        @update="update"
      >
      </form-builder>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">{{ $t('common.base.cancel') }}</el-button>
      <el-button type="primary" :loading="saveLoading" @click="submitForm">{{ isFromEnter ? $t('faultLibrary.startEnter') : $t('common.base.save') }}</el-button>
    </div>
  </base-modal>
</template>
          
<script>
// api
import { 
  solutionGetFields, // 获取解决方案表单字段
  solutionGetData, // 获取解决方案的详细数据 
  solutionCreate, // 新建解决方案
  solutionEdit, // 编辑解决方案
} from '@src/api/Fault';
import * as FaultApi from '@src/api/Fault';

import {ceshi, solutionSearch1, material} from '@src/modules/faultLibrary/mode/solutionGetFields.js'
import * as FormUtil from '@src/component/form/util';
import MsgModel from '@model/MsgModel';
import { message } from '@src/util/message';

import { useFormTimezone } from 'pub-bbx-utils'
const { disposeFormSubmitTime } = useFormTimezone()

export default{
  // 解决方案
  name:'FaultSolution',
          
  data(){
    return {
      loading: false,
      options:[],
      ruleForm: {
        // 父级id
        libraryId:'',
        // 描述
        solution_desc:'',
        // 除了描述外的其他表单数据
        attribute:{}
      },
      // 上级故障描述
      parentDesc:'',
      
      // 表单字段
      fields:[],
      // 用于存储选中知识库的对象数据
      knowledgeData: [],
      saveLoading: false
    }
  },
    
  props: {
    value: {
      type: Boolean,
      default: false
    },
    
    // 新建需要，记录父级id和当前级别
    createFaultData: {
      type: Object,
      default: () => ({})
    },

    // 当前的id
    currentFaultSolutionId: {
      type: String,
      default:''
    },

    // 来源：0:故障树创建（默认）   1:工单附加组件创建（工单附加组件）
    faultSource:{
      type: Number,
      default: 0
    },
    // 工单信息
    task: {
      type: Object,
      default: () => ({})
    },
    isRegister: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    value(value) {
      if(!value) {
        this.initForm()
       }else {
        this.openDialog();
      }
    }
  },
    
  computed:{
    dialogVisible:{
      get(){
        return this.value;
      },
    
      set(val){
        this.$emit('input', val)
      }
    },
    
    
    title:{
      get(){
        return this.isFromEnter ? this.$t('faultLibrary.enterFaultTree') : this.currentFaultSolutionId ? this.$t('faultLibrary.faultObject.createSolution2') : this.$t('faultLibrary.faultObject.createSolution');
      },
    },
    // 工单附加组件创建
    isFaultSource() {
      return this.faultSource === 1;
    },
    dialogBodyStyle() {
      return {
        'height': this.isFaultSource ? 'calc(100vh - 260px);' : '400px',
        'overflow': 'auto'
      };
    },
    formBuilderStyle() {
      return this.isFaultSource ? 'max-height:calc(100vh - 260px);' : 'max-height: 360px;';
    },
    isFromEnter() {
      return this.createFaultData.isStartEntry;
    }
  },
        
  methods: {
    initForm() {
      this.ruleForm = {
        // 父级id
        libraryId:'',
        // 描述
        solution_desc:'',
        // 除了描述外的其他表单数据
        attribute:{}
      }
      this.knowledgeData = []
      this.parentDesc = ''
    },
    /**
     * @description 获取Field
     */
    getField(type){
      let field = this.fields.filter(item => item.formType == type)[0];
      return field;
    },

    openDialog(){
      
      // const { id, parentId, parentDesc } = this.faultEditData || {}

      this.loading = true;
      this.saveLoading = false;
      // 获取表单字段接口
      let port = [ solutionGetFields ]

      // 编辑类型获取详细数据
      if(this.currentFaultSolutionId) {
        // 获取详情数据
        port.push(() => { return solutionGetData({solutionId: this.currentFaultSolutionId}) })
      }else{
        // 新增解决方案时，父组件传递过来的数据
        port.push( this.getInitData )
      }

      Promise
        .all(port.map(item => { return item()}))
        .then(async (res) => {
          // 解决方法描述必填
          res[0].data.forEach(x => {
            if(x.fieldName === 'solution_desc') x.isNull = 0;
          })
          this.fields = [ ...res[0].data ];
          const descField = this.fields.find(v => v.fieldName === 'solution_desc') || {};
          descField.maxlength = 1000
          // todo 本地数据模拟测试的
          // this.fields = [ ...material ]
          // const { solutionDesc, attribute, wikiDataValue, sparePartValue, serviceProjectsValue, materialValue } = solutionSearch1.data.data || res[1]?.data || {}
          res[1].data = await FormUtil.initRichTextContent(this.fields, res[1]?.data || {});
          const { solutionDesc, attribute, wikiDataValue, sparePartValue, serviceProjectsValue, materialValue } = res[1]?.data || {}
          let source = this.currentFaultSolutionId ? { solution_desc: solutionDesc, ...attribute } : {}
          

          let formType = ['subSparePart', 'subServiceItem', 'subMaterials']

          let obj = {
            'subSparePart': sparePartValue,
            'subServiceItem': serviceProjectsValue,
            'subMaterials': materialValue,
          }

          this.ruleForm = FormUtil.initialize(this.fields, source);

          formType.forEach(item => {
            const fieldName = this.getField(item)?.fieldName || '';
            if (!fieldName) return
            const list = (obj[item] || []).map(data => {
              const { id, detailId, attribute } = data
              return { id: detailId, editId: id, ...attribute }
            })
            this.ruleForm[fieldName] = list
          })
          const knowledgeField = this.getField('knowledge')
          if (knowledgeField) {
            const knowledgeFieldName = knowledgeField.fieldName || ''
            this.knowledgeData = wikiDataValue?.map(wikiData => {
              return { id: wikiData.detailId, title: wikiData.attribute?.title, editId: wikiData.id }
            }) || []
            const formData = wikiDataValue?.map(wikiData => wikiData.detailId) || []
            this.ruleForm[knowledgeFieldName] = knowledgeField.setting?.isMulti ? formData : formData[0]
          }

          // 设置表单公共字段
          const { libraryId, libraryDesc, id } = res[1]?.data || {}
          this.ruleForm.libraryId = libraryId;
          this.ruleForm.solutionId = id
          this.parentDesc = libraryDesc
        }).finally(()=>{
          this.loading = false;
        })
    },

    // 封装成异步(为了减少判断)，返回新建解决方案，父组件传递过来的数据
    getInitData(){
      const { parentId, parentDesc } = this.createFaultData || {}
      return new Promise((resolve) => {
        resolve({
          status:0,
          data: {
            libraryId: parentId,
            id: null,
            libraryDesc: parentDesc,
            attribute: {}
          }
        })
      })
    },

    update({ field, newValue, valueObj }) {
      let { fieldName, displayName } = field
      if (this.$appConfig.debug) {
        console.info(`[FormBuilder] => ${displayName}(${fieldName}) : ${JSON.stringify(newValue)}`);
      }

      if(field.fieldName === 'knowledge'){
        this.knowledgeData = valueObj
      }

      this.$set(this.ruleForm, fieldName, newValue)
    },

    // 将系统字段转为接口需要的格式
    switchSystemField(list, solutionDetailType){
      return list.map(item => {
        // const { id } = item
        const noAttrKeys = [ 'id', 'detailId']
        // const keys = Object.keys(item)

        // keys.map(key => {
        //   if(noAttrKeys.includes(key)) return;

        //   attribute.push({
        //     mapKey: key,
        //     mapValue: item[key]
        //   })
        // })
        const attribute = {...item}
        noAttrKeys.forEach(key => {
          delete attribute[key]
        })
        // id：原数据列表返回的id，detailId是该表单记录的该类型控件数据id，attribute自定义字段储存 json
        return { id: item.editId, detailId: item.id, solutionDetailType, attribute }
      })
    },

    // 系统字段提交时的key
    systemSubmitKey(key){
      const obj = {
        'solution_desc': 'solutionDesc',
        'subSparePart': 'sparePartValue',
        'subServiceItem': 'serviceProjectsValue',
        'subMaterials': 'materialValue',
        'knowledge': 'wikiDataValue'
      }
      return obj[key]
    },

    // 系统字段转换为接口需要的格式
    systemFieldToParams(field){
      const { fieldName } = field

      let value = []

      if(fieldName === 'knowledge'){
        value = this.knowledgeData?.map(v => {
          const { id, title, editId } = v
          return {
            id: editId,
            detailId: id,
            solutionDetailType: 4,
            attribute:{ title }
          }
        }) || []
      } else if(['subSparePart', 'subServiceItem', 'subMaterials'].includes(fieldName)){
        const solutionDetailType = ({subSparePart: 1, subMaterials: 2, subServiceItem: 3})[fieldName]
        value = this.switchSystemField(this.ruleForm[fieldName], solutionDetailType)
      } else{
        value = this.ruleForm[fieldName]
      }
      return { 
        key: this.systemSubmitKey(fieldName), 
        value
      }
    },

    // 系统字段集合,因为有的系统字段的isSystem为0，因此这边直接枚举出来
    getSystemFieldsNameArr(){
      return ['knowledge', 'solution_desc', 'subSparePart', 'subServiceItem', 'subMaterials']
    },

    getParams() {
      let attribute = {}
      let systemFieldsAttr = {}

      const systemFieldsNameArr = this.getSystemFieldsNameArr()
      // 将自定义字段放到attribute里
      this.fields.map( item => {
        const { fieldName } = item;

        if(!systemFieldsNameArr.includes(fieldName)){
          attribute[fieldName] = this.ruleForm[fieldName]
        }else{
          const { key, value } = this.systemFieldToParams(item)
          systemFieldsAttr[key] = value
        }
      })

      const { libraryId, solutionId } = this.ruleForm
      return { 
        libraryId, 
        id:solutionId,
        attribute,
        ...systemFieldsAttr,
        enterState: this.faultSource === 1 ? 0 : 1,
        solutionSource: this.faultSource,
      };
    },
    
    async submitForm() {
      try {
        const validateRes = await this.$refs.ruleForm.validate();
        if (!validateRes) return;
        this.saveLoading = true;

        const port = this.currentFaultSolutionId ? solutionEdit : solutionCreate

        const params = disposeFormSubmitTime(this.fields, this.getParams()) // 处理国际化日期时间数据转换
        const res = await port(params);
        
        if(res.status !== 0 ){

          this.$notify.error({
            title: this.$t('common.base.toast'),
            message: res.message,
            duration: 2000,
          });
          return;
        }

        if(this.task.id) {
          // 绑定工单
          const params1 = {
            taskId: this.task.id,
            taskNo: this.task.taskNo,
            faultId: this.createFaultData.parentId,
            solutionId: res.data.id,
            id: this.createFaultData.id,
            objDesc: this.createFaultData.objDesc
          }
          await this.faultBindTask(params1, this.currentFaultDescriptionId);
        }

        this.dialogVisible = false
        this.$emit('operateSuc', res.data)
      } catch(err) {
        console.log('submitForm => err', err)
      } finally {
        this.saveLoading = false;
      }
    },
    // 绑定工单
    faultBindTask(params, isEdit = false) {
      FaultApi.getTaskCardEdit(params).then(res => {
        if (!MsgModel.isSuccess(res)) return message.error(res.message);

      }).catch((error) => {
        console.log('faultBindTask: ', e);
      })
      this.$emit('operateSuc')

      if(this.isFromEnter) {
        this.$emit('startEnter')
      }
    },
  }
}
</script>


<style lang="scss">
.base-mode-wrap .prev-level-des{
   margin-bottom: 12px;
  .label{
    line-height: 1.4;
    padding: 0;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    white-space: nowrap;
    color: #262626;
  }
}
</style>
<style lang="scss" scoped>
::v-deep .base-modal-body {
  overflow: auto;
  padding: 20px;
  .form-builder {
    width: 100%;
    padding: 0;
    .form-item {
      padding-left: 0;
    }
  }
}
</style>